﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Threading;
using System.Data.Linq;

namespace MvcApplication1.Controllers
{
    /// <summary>
    /// 线程单例对象工厂
    /// </summary>
    internal static class DbFactory
    {
        volatile static Dictionary<Thread, string> divDataContext;
        static System.Timers.Timer sysTimer;
        static DbFactory()
        {
            divDataContext = new Dictionary<Thread, string>();
            sysTimer = new System.Timers.Timer(10000);
            sysTimer.AutoReset = true;
            sysTimer.Enabled = true;
            sysTimer.Elapsed += new System.Timers.ElapsedEventHandler(sysTimer_Elapsed);
            sysTimer.Start();
        }

        /// <summary>
        /// 清理上下文
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void sysTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            List<Thread> list = divDataContext
                .Keys
                .Where(item => item.ThreadState == ThreadState.Stopped)
                .ToList();
            if (list != null && list.Count > 0)
            {
                foreach (var i in list)
                {
                    divDataContext[i] = null;
                    divDataContext.Remove(i);
                }
            }
        }
        /// <summary>
        /// 生成对象
        /// </summary>
        /// <returns></returns>
        public static string Intance()
        {

            if (!divDataContext.Keys.Contains(Thread.CurrentThread))
            {
                divDataContext.Add(Thread.CurrentThread, "当前线程名称:"
                       + Thread.CurrentThread.ManagedThreadId.ToString().PadLeft(2, '0')
                       + ",线程总数:"
                       + divDataContext.Count
                       + ",已经结束的总数:"
                       + divDataContext.Keys.Where(item => item.ThreadState == ThreadState.Stopped).Count()
                       + "<hr>");
            }

            return divDataContext[Thread.CurrentThread];
        }
    }

    public class HomeController : Controller
    {
        DataClasses1DataContext db;
        public HomeController()
        {
            db = (DataClasses1DataContext)MvcApplication1.DbFactory.Intance("test");
        }
        public ActionResult Index()
        {

            //for (int i = 0; i < 10; i++)
            //{
            //    var t = new Thread(() =>
            //    {
            //        ViewData["msg"] = ViewData["msg"] + DbFactory.Intance();
            //    });
            //    t.Start();
            //    //Thread.Sleep(1000);
            //}

            return View();
        }

        public ActionResult About1()
        {
            ViewData["msg"] = "当前线程：" + Thread.CurrentThread.ManagedThreadId.ToString();
            Product p = new Product
            {
                ClickCount = 0,
                CreateDate = DateTime.Now,
                ProductName = "test",
                ThreadID = Thread.CurrentThread.ManagedThreadId.ToString(),
            };
            try
            {
                db.Product.InsertOnSubmit(p);
                db.SubmitChanges();

            }
            catch (Exception)
            {
                //出现异常后，应该将当前数据上下文清空
                // db.Connection.Close();
                //当出现异常后，马上把线程数据上下文从字典中去除
                MvcApplication1.DbFactory.ClearContextByThread(Thread.CurrentThread);
                foreach (System.Data.Linq.ObjectChangeConflict occ in db.ChangeConflicts)
                {
                    // 使用当前数据库中的值，覆盖Linq缓存中实体对象的值  
                    occ.Resolve(System.Data.Linq.RefreshMode.OverwriteCurrentValues);
                    // 使用Linq缓存中实体对象的值，覆盖当前数据库中的值  
                    occ.Resolve(System.Data.Linq.RefreshMode.KeepCurrentValues);
                    // 只更新实体对象中改变的字段的值，其他的保留不变  
                    occ.Resolve(System.Data.Linq.RefreshMode.KeepChanges);
                }
                db.SubmitChanges();
            }



            return View();
        }

        public ActionResult About2()
        {
            ViewData["msg"] = "当前线程：" + Thread.CurrentThread.ManagedThreadId.ToString();
            Order_Info order = new Order_Info
            {
                CreateDate = DateTime.Now,
                UserID = 0,
                ThreadID = Thread.CurrentThread.ManagedThreadId.ToString()
            };
            db.Order_Info.InsertOnSubmit(order);
            db.SubmitChanges();
            return View();
        }


        [HttpPost]
        public ActionResult upfile()
        {
            string savepath = null;
            int iTotal = Request.Files.Count;
            if (iTotal == 0)
            {
                Response.Write("<script> alert('没有数据');</script>");
            }
            else
            {
                for (int i = 0; i < iTotal; i++)
                {
                    HttpPostedFileBase file = Request.Files[i];
                    if (file.ContentLength > 0 || !string.IsNullOrEmpty
                         (file.FileName))
                    {
                        //保存文件
                        string diect = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Upload");
                        string filename = Path.GetFileName(file.FileName);
                        savepath = string.Format("{0}\\{1}", diect, Guid.NewGuid().ToString() + filename);
                        file.SaveAs(savepath);
                    }
                }
            }
            return RedirectToAction("Index", new { img = savepath });

        }
    }
}
